package cn.com.Servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //设置ContentType字段值
            response.setContentType("text/html;charset=UTF-8");
            //创建DiskFileItemFactory工厂对象
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //创建ServletFileUpload对象
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            fileUpload.setHeaderEncoding("utf-8");
            //解析请求
            List<FileItem> fileItems=fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
               if (fileItem.getSize()==0){
                    //未选择上传文件，跳转到失败页面
                    response.sendRedirect(request.getContextPath()+"/updefeate.jsp");
                    return;
                }
                if(!fileItem.isFormField()){
                    //得到文件名
                    String filename = fileItem.getName();
                    String webpath="/upload/";
                    String realPath = request.getSession().getServletContext().getRealPath(webpath+filename);
                    File file=new File(realPath);
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                    //读的是上传的文件
                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out=new FileOutputStream(file);
                    byte[] bytes=new byte[1024];
                    int len;
                    while ((len=in.read(bytes))>0){
                        out.write(bytes,0,len);
                    }
                    in.close();
                    out.close();
                    fileItem.delete();

                }
            }
            System.out.println("+++++++++++");
            //跳转成功页面
            response.sendRedirect(request.getContextPath()+"/upsucess.jsp");
        } catch (FileUploadException e) {
            //跳转失败页面
            response.sendRedirect(request.getContextPath()+"/updefeate.jsp");
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
